package leetcode_2501_2600;

import java.util.Arrays;
import java.util.function.Predicate;

public class LeeCode_2517 {
    public static void main(String[] args) {
        System.out.println(maximumTastiness(new int[]{13, 5, 1, 8, 21, 2}, 3));
        System.out.println(maximumTastiness(new int[]{1,3,1}, 2));
    }
    private static int maximumTastiness(int[] price, int k) {
        Arrays.sort(price);
        int n = price.length;
        if (k == 2)
            return price[n - 1] - price[0];
        int l = 0, r = (price[n - 1] - price[0]) / (k - 1) + 1;
        while (l + 1 < r){
            int m = l + (r - l) / 2;
            if (check(price, m, k)){
                l = m;
            }else {
                r = m;
            }
        }
        return l;
    }

    private static boolean check(int[] price, int m, int k){
        int count = 1, pre = price[0], n = price.length;
        for (int i = 1; i < n; i++) {
            if (price[i] >= pre + m){
                count++;
                pre = price[i];
            }
            if (count == k)
                return true;
        }
        return false;
    }
}
